//index.js
//获取应用实例
var app = getApp()
var QQMapWX = require('../../resource/js/qqmap-wx-jssdk.min.js');
var qqmapsdk;
Page({
	data: {
		root:'',
		siteroot:app.setting.siteroot,
		att_url:app.setting.att_url,
		syscolor:app.setting.syscolor,
		isnodata:false,
		newsloading:true,
		hotloading:true,
		recommandloading:true,
		account:app.setting.account,
		show_coupon:true,
		page:1,
		showgotop:false,
		couponicon:'orange',//red,orange,green,hui
		pagetitle:app.setting.title,
		nodata_pic:'../core/resource/images/index_nodata.jpg'
	},
	onReady: function (){
	},
	onPullDownRefresh: function (){
		var the=this;
		var opt={};
		the.onLoad(opt);
		setTimeout(function(){
			wx.stopPullDownRefresh()
		},1000);
	},
	onLoad: function (opt){
		var page=this;
		var page_js='';
		var footer='';
		var diydata={page_js};
		var footer={footer};
		wx.setNavigationBarTitle({'title':page.data.pagetitle});
		var route=page.route;
		page.setData({
			route:route,
			apptitle:app.setting.title,
		});
		if(!app.plugin_name){
			var path=route.slice(0,-6).split('/');
			app.plugin_name=path.shift();
		}
		//首页必须指定路径
		app.access.plugin='jy_weishop';
		app.access.action='index';
		app.access.op='';
		//console.log('app.access');console.log(app.access);
		console.log('opt');console.log(opt);
		if(opt){
			app.access.query =app.util.made_query(opt);
			if(opt.room_id){
				app.room_id=opt.room_id;
				let livePlayer = requirePlugin('live-player-plugin')
				livePlayer.getShareParams().then(res => {
					app.share_openid=res.share_openid;
					console.log('getShareParams');console.log(res);
				})
				.catch(err => {
					console.log('getShareParams', err)
				})
			}
			if(opt.isgoshare){
				page.setData({
					ShowGoshare:true,
				});
			}
		}
		app.access.query += '&newapp=1';
		if(app.share_openid){
			app.access.query += '&share_openid='+app.share_openid;
		}
		if(app.room_id){
			setTimeout(()=>{
				page.getpagedata();
			},200);
        }else{
			setTimeout(()=>{
				page.getpagedata();
			},100);
		}
	},
	getpagedata: function (){
			var page=this;
			var page_js='';
			var footer='';
			var diydata={page_js};
			var footer={footer};
			app.util.get(app.access,function(pagedata){
			console.log('index');console.log(pagedata);
			pagedata.params=pagedata.params?pagedata.params:{'order':'ishot'}
			pagedata.issocketmsg=false;
			pagedata.isno_coupontop=1;
			pagedata.showtype=0;
			page.setData({
				pluginnav:app.session.menus,
				pagedata:pagedata,
				action:'jy_weishop/index/',
				diydata:diydata,
				footer:footer,
				nodatapic_close:true,
				ShowAuthM:pagedata.show_setmember==2?true:false,
				root:''
			});
			//获取弹幕
			page.gettanmus();
			setTimeout(()=>{
					page.get_list(true);
					page.get_couponlist(true);
					page.get_livelist(true);
					page.get_recommands(true);
					page.get_newsgoods(true);
					page.get_hot_goods(true);
					if(!app.lat_lng && !app.pcd){
						setTimeout(()=>{
							var pagedata=page.data.pagedata
							if(!pagedata.merchlist || pagedata.merchlist.length==0){
								page.getmerchs(1);
							}
						},1000);
						if(!pagedata.pcd.street){
							page.getlocation();
						}
					}else{
						if(app.pcd){
							console.log('app.pcd');console.log(app.pcd);
							page.setData({
								'pagedata.pcd':app.pcd,
								'pagedata.street':app.pcd.street,
							})
						}
						page.getmerchs(1);
					}
			},100);
		});
	},
	get_recommands: function (){
		var page=this;
		app.util.get('jy_weishop/get_data/getrecommands/',function(res){
			//console.log('coupon');console.log(pagedata);
			page.setData({
				'pagedata.recommand_list':res.list,
				recommandloading:false,
			});
		});
	},
	get_newsgoods: function (){
		var page=this;
		app.util.get('jy_weishop/get_data/getnewsgoods/',function(res){
			//console.log('coupon');console.log(pagedata);
			page.setData({
				'pagedata.new_list':res.list,
				newsloading:false,
			});
		});
	},
	get_hot_goods: function (){
		var page=this;
		app.util.get('jy_weishop/get_data/gethot_goods/',function(res){
			//console.log('coupon');console.log(pagedata);
			page.setData({
				'pagedata.hot_list':res.list,
				hotloading:false,
			});
		});
	},
	get_couponlist: function (){
		var page=this;
		app.util.get('jy_weishop/coupon.index/',function(pagedata){
			//console.log('coupon');console.log(pagedata);
			page.setData({
				couponlist:pagedata.list,
			});
		});
	},
	get_livelist: function (){
		var page=this;
		var pagedata=page.data.pagedata
		app.util.get('jy_weishop/sale.live_index/getlist/num=2',function(res){
			//console.log('get_livelist');console.log(res);
			page.setData({
				'pagedata.livelist':res.list,
			});
		});
	},
	gorooms:function(e){
		var data=e.currentTarget.dataset;
		var customParams = encodeURIComponent(JSON.stringify({'path': 'jy_weishop/sale/live_index/index','fromroomid': data.roomsid}));
		wx.navigateTo({
			url: 'plugin-private://'+app.live_appid+'/pages/live-player-plugin?room_id='+data.roomsid+'&open_share_ticket=1'+'&custom_params='+customParams
		})
	},
	gosearch:function(){
		var the=this;
		var pagedata=the.data.pagedata;
		pagedata.params.keyword=pagedata.params.keyword?pagedata.params.keyword:'';
		wx.navigateTo({
			url: '/jy_weishop/goods/index/index?gosearch=1&keyword='+pagedata.params.keyword
		})
	},
	getmerchs: function (){
		var the=this;
		var lat_lng=app.lat_lng?app.lat_lng:{};
		app.util.get('jy_weishop/get_data/getmerchs/limit=5&lat='+lat_lng.lat+'&lng='+lat_lng.lng,function(res){
			//console.log('getmerchs');console.log(res);
			the.setData({
				'pagedata.merchlist':res.list,
				merchsloading:false,
			});
		});
	},
	getlocation:function(isup){
		var the=this
		var pagedata=the.data.pagedata
		//获取区域城市
		qqmapsdk = new QQMapWX({
            key: pagedata.qqmap_ak?pagedata.qqmap_ak:'SN2BZ-MKT32-22SU7-COVX6-ZYXAQ-OEF6D'
        });
		app.util.location(function(lv){
			//console.log('location');console.log(lv)
			//缓存坐标
			app.lat_lng={lat:lv.latitude,lng:lv.longitude}
			pagedata.params.showtype=pagedata.showtype;
			pagedata.params.lat=lv.latitude;
			pagedata.params.lng=lv.longitude;
			the.setData({
				'pagedata.params':pagedata.params,
					
			});
			the.getmerchs(1);
			if(app.pcd && !isup){
				the.setData({
					'pagedata.pcd':app.pcd,
					'pagedata.street':app.pcd.street,
				})
				return false;
			}
			qqmapsdk.reverseGeocoder({
					location:{latitude:lv.latitude,longitude:lv.longitude},
					success:function(res){
						//console.log('location');console.log(res)
						if(res.result.address_component.province){
							 pagedata.pcd.province = res.result.address_component.province
						}
						if(res.result.address_component.city){
							pagedata.pcd.city = res.result.address_component.city
						}
						if(res.result.address_component.district){
							pagedata.pcd.district = res.result.address_component.district
						}
						pagedata.pcd.street=res.result.formatted_addresses.recommend?res.result.formatted_addresses.recommend:res.result.address_component.street;
						the.setData({
							'pagedata.pcd':pagedata.pcd,
							'pagedata.street':pagedata.pcd.street,
						})
						//缓存PCD
						app.pcd=pagedata.pcd
						if(isup){
							app.util.message('定位成功');
						}
					},
					fail: function(res) {
						console.log(res);
					},
					complete: function(res) {	
					}
			});
		},'gcj02');
	},
	get_list:function(e){
		var the=this;
		the.setData({
				loading:true
		});
		var page = the.data.page
		var pagedata=the.data.pagedata
		var isnodata = the.data.isnodata
		if(e){
			if(e.currentTarget){
				var data=e.currentTarget.dataset;
				if(data.type=='price'){
					pagedata.params.order='price';
					pagedata.params.order_type=pagedata.params.order_type?0:1;
				}else if(data.type=='sales'){
					pagedata.params.order='sales';
				}else if(data.type=='ishot'){
					pagedata.params.order='ishot';
				}else if(data.type=='new'){
					pagedata.params.order='new';
				}else{
					pagedata.params.order='default';
				}
				if(data.pid){
					pagedata.params.pcate=data.pid
					pagedata.params.pid=data.pid
					pagedata.params.ccate=0
					pagedata.params.cid=0
				}
				if(data.cid){
					pagedata.params.ccate=data.cid
					pagedata.params.cid=data.cid
				}
				if(data.index || data.index==0){
					the.setData({
						'pagedata.groupkey':data.index
					});
				}
			}
			page = 1;
			pagedata.list=[];
			isnodata=false;
		}else{
			if(isnodata){
				return false;
			}
		}
		var query='page='+page;
		var more_query=app.util.made_query(pagedata.params);
		if(more_query){
			query+='&'+more_query;
		}
		console.log(query);
		app.util.get('jy_weishop/goods.index/getlist/'+query,function(res){
			//console.log('query');console.log(res);
			if(res=='none'){
				the.setData({
					isnodata:true,
					loading:false,
					'pagedata.params':pagedata.params,
					'pagedata.list':pagedata.list,
				});
			}else{
				pagedata.list = pagedata.list.concat(res)
				page++
				the.setData({
					'pagedata.list':pagedata.list,
					'products':pagedata.list,
					'pagedata.params':pagedata.params,
					page:page,
					isnodata:isnodata,
					loading:false,
				});
				if(the.data.diydata.page_js===undefined){
					the.setData({
						'products':pagedata.list,
					});
				}
			}
			
		});
	},
	//翻页
	onReachBottom: function () {
		var the=this;
		var isnodata=the.data.isnodata
		var loading=the.data.loading
		if(!isnodata && !loading){
			the.get_list()
		}
	},
	onPageScroll:function (e) { // 获取滚动条当前位置
		var showtopnav=this.data.showtopnav
		var showgotop=this.data.showgotop
	  if (e.scrollTop > 700 && !showgotop) {
        this.setData({
          showgotop: true
        })
      }
	  if(e.scrollTop < 700 && showgotop){
		this.setData({
          showgotop: false
        })  
	  }
	},
	goTop:function(){
		wx.pageScrollTo({
		  scrollTop: 0,
		  duration: 300
		})
	},
	scancode: function(){
		wx.scanCode({
		  success (res) {
			 wx.navigateTo({'url':res.path});
		  }
		})
	},
	bindclosed:function(){
		this.setData({
			closed:1
		});
	},
	closed_coupon:function(){
		this.setData({
			show_coupon:false
		});
	},
	addtocartall:function(e){
		var the =this
		var pagedata =the.data.pagedata
		var data=e.currentTarget.dataset;
		app.util.post('jy_weishop/goods.detail/addtocart/',{'goodsid':data.goodsid},function(res){
				if(app.session.menus && app.session.menus.length>0){	
					for(var i=0;i<app.session.menus.length;i++){
						if(app.session.menus[i].action=='jy_weishop/member.cart/'){
							app.session.menus[i].badge++
							the.setData({
								pluginnav:app.session.menus,
							})
						}
					}
				}
				app.util.msg('添加成功');
		});
	},
	addtocart:function(e){
		var the =this
		var pagedata =the.data.pagedata
		var data=e.currentTarget.dataset;
		app.util.showLoading('加入中...');
		app.util.post('jy_weishop/member.cart/addtocart/',data,function(res){
				pagedata.hot_list[data.index].carttotal++;
				pagedata.hot_list[data.index].cartid=res.id;
				app.util.hideLoading()
				the.setData({
						'pagedata.hot_list':pagedata.hot_list,
				})
				//console.log(pagedata.list)
				if(app.session.menus && app.session.menus.length>0){	
					for(var i=0;i<app.session.menus.length;i++){
						if(app.session.menus[i].action=='jy_weishop/member.cart/'){
							app.session.menus[i].badge++
							the.setData({
								pluginnav:app.session.menus,
							})
						}
					}
				}
				app.util.msg('添加成功');
		});
	},
	minus:function(e){
		var the=this
		var data=e.currentTarget.dataset;
		var pagedata = the.data.pagedata
		app.util.showLoading('减少中...');
		if(pagedata.hot_list[data.index].carttotal <=1){
			app.util.post('jy_weishop/member.cart/minus/',{'id':data.id,'wxapp':1},function(res){
				pagedata.hot_list[data.index].carttotal=0;
				wx.hideLoading()
				the.setData({
					'pagedata.hot_list': pagedata.hot_list,
					tocart:false,
				})
				//console.log(pagedata.list);
				if(app.session.menus && app.session.menus.length>0){	
					for(var i=0;i<app.session.menus.length;i++){
						if(app.session.menus[i].action=='jy_weishop/member.cart/'){
							app.session.menus[i].badge--
							the.setData({
								pluginnav:app.session.menus,
							})
						}
					}
				}
			});
		}else{
			var cart=pagedata.hot_list[data.index];
			if(cart.outtype==1 && parseInt(pagedata.hot_list[data.index].carttotal) + parseInt(cart.order_goodscount)<=parseInt(cart.usermaxbuy)){
					pagedata.hot_list[data.index].outtype=false;
			}
			if(cart.outtype==2 && parseInt(pagedata.hot_list[data.index].carttotal)<=cart.kucun){
					pagedata.hot_list[data.index].outtype=false;
			}
			if(cart.outtype==4 && parseInt(pagedata.hot_list[data.index].carttotal)<=cart.maxbuy){
					pagedata.hot_list[data.index].outtype=false;
			}
			if(parseInt(pagedata.hot_list[data.index].carttotal)<cart.minbuynum){
				pagedata.hot_list[data.index].outtype=3;
				pagedata.hot_list[data.index].outnumtitle='单次最低购买'+cart.minbuynum+'件';
			}			
			app.util.post('jy_weishop/member.cart/minus/',{'id':data.id},function(res){
				app.util.hideLoading()
				pagedata.hot_list[data.index].carttotal--;
				the.setData({
				  'pagedata.hot_list': pagedata.hot_list,
				  tocart:false,
				})
				if(app.session.menus && app.session.menus.length>0){	
					for(var i=0;i<app.session.menus.length;i++){
						if(app.session.menus[i].action=='jy_weishop/member.cart/'){
							app.session.menus[i].badge--
							the.setData({
								pluginnav:app.session.menus,
							})
						}
					}
				}
			});
		}
	},
	plus:function(e){
		var the=this
		var data=e.currentTarget.dataset;
		var pagedata = the.data.pagedata
		var cart=pagedata.hot_list[data.index];
		if(cart.option && parseInt(cart.total)<=parseInt(cart.carttotal)){
			app.util.msg('超库存，不能再加了！');
			return false;
		}
		app.util.showLoading('加入中...');
		if(cart.outtype==3 && parseInt(pagedata.hot_list[data.index].carttotal)>=cart.minbuynum){
			pagedata.hot_list[data.index].outtype=false;
		}		
		app.util.post('jy_weishop/member.cart/plus/',{'id':data.id},function(res){
			app.util.hideLoading()
			pagedata.hot_list[data.index].carttotal++;
			the.setData({
				  'pagedata.hot_list': pagedata.hot_list,
				  tocart:false,
			})
			if(app.session.menus && app.session.menus.length>0){	
					for(var i=0;i<app.session.menus.length;i++){
						if(app.session.menus[i].action=='jy_weishop/member.cart/'){
							app.session.menus[i].badge++
							the.setData({
								pluginnav:app.session.menus,
							})
						}
					}
			}
		});
	},
	closedsales:function(evt){
		var the=this;
		var pagedata=the.data.pagedata
		pagedata.closedsales=pagedata.closedsales!=1?1:0;
		the.setData({
			'pagedata.closedsales':pagedata.closedsales
		})
	},
	gettanmus:function() {
		var the=this;
		var pagedata=the.data.pagedata
		if(!pagedata.issocketmsg){
				app.util.get('jy_weishop/get_data/gettanmus/page='+pagedata.tanmuspage,function(res){
							pagedata.tanmus=res.list
							if(pagedata.tanmus.length>0){
								pagedata.tanmuspage++;
								pagedata.nowmsgid=0;
								the.setData({
									'pagedata.issocketmsg':pagedata.issocketmsg,
									'pagedata.tanmus':pagedata.tanmus,
									'pagedata.nowmsgid':pagedata.nowmsgid
								})
								the.up_oldtanmu();
							}
				});
		}
	},
	up_oldtanmu:function() {
		var the=this;
		var pagedata=the.data.pagedata
		var i=pagedata.nowmsgid;
		if(i<pagedata.tanmus.length){
				the.set_tanmu(pagedata.tanmus[i].nickname,pagedata.tanmus[i].avatar,pagedata.tanmus[i].time);
		}else{
				the.gettanmus();
		}
	},
	set_tanmu:function(nickname,avatar,time) {
		var the=this;
		var pagedata=the.data.pagedata
		pagedata.nowmsgid++
		the.setData({
				showtanmus:true,
		})
		setTimeout(function(){
			the.setData({
				transition:true,
			})	
		},300);
		setTimeout(function(){
			the.setData({
				showtanmus:false,
			})	
		},2000);
		setTimeout(function(){
			//等待5秒，如果没有新的订单消息，就弹储备订单消息
			pagedata.issocketmsg=pagedata.issocketmsg?pagedata.issocketmsg:false;
			the.setData({
				'pagedata.issocketmsg':pagedata.issocketmsg,
				'pagedata.nowmsgid':pagedata.nowmsgid,
				transition:false
			})
			if(!pagedata.issocketmsg){
				the.up_oldtanmu();
			}
		},4000);
	},
	upshowtype:function(e){
		var the=this;
		var pagedata=the.data.pagedata;
		var data=e.currentTarget.dataset;
		pagedata.showtype=data.type
		if(pagedata.showtype==0){
			pagedata.params.order='ishot';
			the.get_list(1);
		}else if(pagedata.showtype==2){
			pagedata.params.order='price';
			the.get_list(1);
		}
		the.setData({
			'pagedata.showtype':pagedata.showtype,
			'pagedata.params.order':pagedata.params.order,
		});
	},
	// 搜索框文本内容的显示
	keyword: function (e) {
		var the = this
		the.setData({
		  'pagedata.params.keyword': e.detail.value
		})
	},
	lianxikefu: function(e) {
		var the=this;
		var data=e.currentTarget.dataset;
		//企业微信
		wx.openCustomerServiceChat({
			  extInfo: {url: data.linkurl},
			  corpId: data.corpid,
			  success(res) {
				  console.log(res)
			  },
			  fail(res) {
				  console.log('fail'); console.log(res)
				  app.util.message(res.errMsg);
			  }
		})
    },
	setiswelcome:function(){
		var the=this;
		var pagedata= the.data.pagedata
		pagedata.iswelcome=pagedata.iswelcome==1?0:1;
		the.setData({
			'pagedata.iswelcome':pagedata.iswelcome
		})
	},
  	click:function(evt){
		var the=this;
		//用户点击事件 data.func 为方法名，data.params 为调用参数！
		var data=evt.currentTarget.dataset;
		if(data.func=='tab'){
			the.setData({tabindex:data.index});
		}
		app.util[data.func](data.params);
	},
	onChooseAvatar:function(e){
		//获取头像
		var the=this;
		var avatarUrl= e.detail.avatarUrl
		the.setData({
			avatarUrl:avatarUrl
		})
		app.avatarUrl=avatarUrl
	},
	info_login:function(e){
		//根据openid为用户登陆，此处尝试获取用户信息
		var the=this;
		app.util.getUserInfo(e,function(res){
			if(res && res.userInfo){
				app.isgetUserInfo=true
				the.setData({
					ShowAuthM:false
				})
				the.onLoad();
			}else{
				return false;
			}
		});
	},
	mobile_login:function(e){
		//根据openid为用户登陆，此处尝试获取用户手机号
		var the = this
		var pagedata= the.data.pagedata
		app.util.post('core/member.login/wxapp_login/return_mobile=1',e.detail,function(res){
			the.setData({
				ShowAuthM:false
			})
		});
	},
	closeAuthM:function(){
		var the=this;
		the.setData({
			ShowAuthM:false
		})
	},
	formSubmit:function(event){
		var data=event.detail.value;
		app.util.post('post',data);
	},
	click_tab:function(evt){
		//用户点击事件 data.func 为方法名，data.params 为调用参数！
		var data=evt.currentTarget.dataset;
		app.util.tab(data.params);
	},
	onShareAppMessage: function (res) {
		var the = this
		var pagedata = the.data.pagedata
		if (res.from === 'button') {
		}
		var path=the.data.route+'?'+app.access.query;
		if(app.access.op){
			path +='&op='+app.access.op;
		}
		if(pagedata.fromuser){
			path +='&fromuser='+pagedata.fromuser;
		}
		return {
		  title: the.data.pagetitle,
		  path: path,
		  desc: app.setting.sharedesc,
		  success: function(res) {
		  },
		  fail: function(res) {
		  }
		}
	},
	onShareTimeline: function (res) {
		var the = this
		var pagedata = the.data.pagedata
		var query=app.access.query
		if(app.access.op){
			query +='&op='+app.access.op;
		}
		if(pagedata.fromuser){
			query +='&fromuser='+pagedata.fromuser;
		}
		query +='&isgoshare=1'
		return {
		  title: the.data.pagetitle,
		  query: query,
		  desc: app.setting.sharedesc,
		  success: function(res) {
		  },
		  fail: function(res) {
		  }
		}
	},
});